export async function proxyFetch(
    input: RequestInfo | URL,
    init?: RequestInit,
): Promise<Response> {
    const url = new URL(input instanceof Request ? input.url : input);
    const method = init?.method || "GET";

    const proxyUrl = new URL("/proxy", window.location.origin);
    proxyUrl.searchParams.set("url", url.toString());
    proxyUrl.searchParams.set("method", method);

    const headers = new Headers(init?.headers);

    try {
        const response = await fetch(proxyUrl.toString(), {
            method: "POST",
            headers,
            body:
                method !== "GET" && method !== "HEAD"
                    ? init?.body
                    : undefined,
        });

        return response;
    } catch (error) {
        throw new Error(
            `Proxy fetch failed: ${
                error instanceof Error ? error.message : String(error)
            }`,
        );
    }
}
